//1.从Pinia中导入defineStore函数
import request from "@/utils/request";
import { defineStore } from "pinia";
//2.定义用户状态管理实例并导出
export const useUserStore = defineStore("userStore", {
    //1.state属性 保存数据状态
    state: () => ({//保存用户登录状态
        userinfo: {
            username: '',
            imgPath: '',
        },
        token: "",
        isLogin: false,
    }),
    //计算数据：使用state中数据，根据state中原始数据派生出新的数据（不推荐修改state中数据）
    getters: {
        //判断用户是否登录
        checkLogin: (state) => state.userinfo.username != null && state.userinfo.username != '',
        getUsername: (state) => state.userinfo.username,//获取登录用户名
        getImgPath: (state) => state.userinfo.imgPath,
        isToken: (state) => state.token != null && state.token != ""
    },
    actions: {//修改state中数据
        /**
         * 用户登录方法，如果登录成功则把用户信息保存到state中相关属性中
         * userForm是自定义参数名=>是函数变量
         */
        async login(userinfo: any) {
            //实现登录细节操作
            let response = await request.post("/login", userinfo);
            if (response.data.success) {
                this.userinfo.username = response.data.data.username;
                this.userinfo.imgPath = response.data.data.imgPath;
            } else {//登录失败
                this.userinfo.username = "";
                this.userinfo.imgPath = "";
            }
            return response.data;
        },
        //用户退出函数
        loginOut() {
            this.userinfo.username = "";
            this.userinfo.imgPath = "";
            this.token = "";
        },
        //给token设值
        setToken(token: any) {
            this.token = token;
        }
    },
    // pinia数据持久化
    persist: {
        enabled: true,//开启持久化存储
        storage: sessionStorage,//存储位置，默认为localStorage
    }
})